﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Telerik.Web.Mvc;
using OBUCare.Core.Common;
using OBUCare.Web.Infrastructure;

namespace OBUCare.Web.Controllers
{
   
    public class UploadController : Controller
    {
        static string tempFolder = UIUtility.GetTempFolderPath();

        public static string GetFilePathInTempFolder(string fileName)
        {
            return Path.Combine(tempFolder, fileName);
        }

        public ActionResult Save(IEnumerable<HttpPostedFileBase> upload_attachments)
        {
            // The Name of the Upload component is "attachments" 
            List<string> fileList = new List<string>();
            foreach (var file in upload_attachments)
            {
                // Some browsers send file names with full path. This needs to be stripped.
                var fileName = Path.GetFileName(file.FileName);

                string newFileName = fileName.GetNewRandomFileName();
                string contentType = file.ContentType;
                var physicalPath = GetFilePathInTempFolder(newFileName);

                // The files are not actually saved in this demo
                file.SaveAs(physicalPath);

                fileList.Add(newFileName);
            }

            // When returning JSON the mime-type must be set to text/plain
            return Json(new { status = "OK",Files=fileList }, "text/plain");
        }

        public ActionResult Remove(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"
            //foreach (var fullName in fileNames)
            //{
            //    var fileName = Path.GetFileName(fullName);
            //    var physicalPath = Path.Combine(Infrastructure.Utility.GetTempFolderPath(), fileName);

            //    // TODO: Verify user permissions
            //    if (System.IO.File.Exists(physicalPath))
            //    {
            //        // The files are not actually removed in this demo
            //        // System.IO.File.Delete(physicalPath);
            //    }
            //}
            // Return an empty string to signify success
            return Json(new { status = "OK"}, "text/plain");
        }             
    }
}
